// 使用原生的方式完成的安卓文件js
// noinspection JSValidateTypes

import {requestAndroidPermission} from "@/common/permission.js"


// 导入所需的类
export const File = plus.android.importClass("java.io.File");
const FileInputStream = plus.android.importClass("java.io.FileInputStream");
const BufferedReader = plus.android.importClass("java.io.BufferedReader");
const InputStreamReader = plus.android.importClass("java.io.InputStreamReader");

// 获取文件夹下的所有内容,仅处理一个层级,不返回文件夹,仅返回文件
export async function getFiles(path) {
    const r = await requestAndroidPermission('android.permission.READ_EXTERNAL_STORAGE')
    if (r !== 1) {
        return null
    }
    const files = [];
    const file = new File(path);
    const fileList = file.listFiles();
    for (let i = 0; i < fileList.length; i++) {
        const f = fileList[i];
        if (f.isFile()) {
            files.push(f);
        }
    }
    return files;
}

// 获取指定文件的文件内容并返回出去
export async function readFile(path) {
    const r = await requestAndroidPermission('android.permission.READ_EXTERNAL_STORAGE')
    if (r !== 1) {
        await uni.showToast({title: '请允许读取文件', icon: 'none'})
        return null
    }

    const file = new File(path);
    const inputStream = new FileInputStream(file);
    const reader = new BufferedReader(new InputStreamReader(inputStream));
    let line = "";
    let result = "";
    while ((line = reader.readLine()) != null) {
        result += line;
    }
    reader.close();
    return result;
}
